<?php
/**********************************************
* 파일명: lib.php
* 설  명: 스킨매니저에서 사용하는 함수와 기본설정값이 포함되어 있습니다.
* 사용권한 설정  : $useMember = true;   //false : 블로그 개설자만 스킨매니저 사용가능 가능. true :블로그 운영자 누구나 사용가능. 
***********************************************/

// 스킨매니저 플러그인 사용권한 설정 
$useMember = false;   


// 스킨매니저 플러그인 기본설정값 - 수정하지 마세요.
$imgUrl = $pluginURL."/image/";  		//플러그인 이미지폴더
$start	= ROOT.'/skin/';						//탐색 시작 위치 (상대경로)
$limit	= 50;										//폴더 당 표시 할 최대 서브폴더
$width ="148px";   							//스킨 이미지파일 표시
$height ="130px";  							//스킨 이미지파일 표시
$cols	= 4;										//한줄에 표시 할 이미지 갯수
$exts	= "gif|jpg|jpeg|png|bmp|swf";	//표시 할 이미지 파일포맷
$skinfiles ="xml|html|css|js"; 			//편집가능한 텍스트 파일포맷
$kkk =0;	
$curdir_id = '';

if(!is_dir($start)) {
	mkdir($start);
	@chmod($start,0777);
}

function TT_SkinManagerGetSkins($startdir,$depth=0,$root=0,$curdir='',$skinname='')
{
global $limit, $kkk, $curdir_id,$start,$pluginURL,$pluginMenuURL;
$start	= ROOT.'/skin/';
$dh=@opendir($startdir);

	$block ="";
	for($i=0;$i<$depth;$i++)
	{
	$block.="<img src=".$pluginURL."/image/sf_blank.gif  border=0 alt='blank' />";
	}

	unset($buff);

		$position="";
		$visibility="visible";


	while($dir=@readdir($dh))
	{
		if($dir=="." || $dir==".." || $dir=="customize")
		{
		continue;
		}
		if(!is_dir("$startdir/$dir") || !$dh2=@opendir("$startdir/$dir"))
		{
		continue;
		}

	$buff[]=$dir;	

	@closedir($dh2);
	}

	if($curdir."/" == "$startdir/$dir"){
		$curdir_id = $kkk -1;
	}

	 usort($buff, "strcasecmp");
	//@sort($buff);

	if($depth > 0)  echo "<ul>".CRLF;
	for($i=0;$i<sizeof($buff);$i++)
	{	
	$thisdir = $startdir.$buff[$i]."/";
	if(eregi($thisdir, $curdir)) 	echo '<li class="seleted">'.CRLF; 
	else echo '<li >'.CRLF; 

	if($depth ==0) {
		$skinname = $buff[$i];
		$skinfolder = $buff[$i]."/";
		echo "<a onfocus='this.blur()' 	href='#void' onclick=\"javascript:js_skin_submit('".$skinname."','".$skinfolder."');return false;\">";
	}else{
		$skinfolder = str_replace($start,"",$thisdir);
		echo "<a onfocus='this.blur()' 	href='#void' onclick=\"javascript:js_skin_submit('".$skinname."','".$skinfolder."');return false;\">";
	}
	echo $buff[$i] ."</a>".CRLF;
	if(eregi($thisdir, $curdir)) 	TT_SkinManagerGetSkins($thisdir,$depth+1,$root."_". $i, $curdir, $skinname);
	echo '</li>'.CRLF;
	$kkk = $kkk + 1;
	}
	if($depth > 0)  echo "</ul>".CRLF;

@closedir($dh);
return $kkk; 
}

function TT_SkinManagerEncode($str,$mode)
{
	if($mode=="e")
	{
	$str	= urlencode($str);
	}

	if($mode=="d")
	{
	$str	= urldecode($str);
	}

return $str;
}

function TT_SkinManagerMsg($str)
{
echo "
<script language=\"JavaScript\" type=\"text/javascript\">
<!--
	alert(\"$str\");
	document.reg.skin.value = '';
	document.reg.skinfolder.value = '';
	document.reg.submit();
//-->
</script>";
}

function TT_SkinManagerErrorMsg($str)
{
echo "
<script language=\"JavaScript\" type=\"text/javascript\">
<!--
	alert(\"$str\");
//-->
</script>";
exit;
}

function TT_SkinManagerDeletefolder($dir){
	$d=dir($dir);
	while($f=$d->read()){

		if($f!="."&&$f!=".."){
			if(is_dir($dir.$f)){
				TT_SkinManagerDeletefolder($dir.$f."/");
				rmdir($dir.$f);
			}
			if(is_file($dir.$f)){
				unlink($dir.$f);
			}
		}
	}
	$d->close();
}

function TT_SkinManagerServerURL(){
		return "http://www.tattertools.com/ko/bbs/skinmanager/";
}

function TT_SkinManagerGetSkinData($page=1,$category=""){
		global $total,$pages;
		$ttskinUrl = TT_SkinManagerServerURL()."?page=".$page."&category=".$category;
		requireComponent('Eolin.PHP.HTTPRequest');		
		$request = new HTTPRequest($ttskinUrl);
		if ($request->send()){
			$tmp = $request->responseText;
			 return fetchTTSkinXmlVal($tmp);
		}
		return null;
	}

	function TT_SkinManagerGetSkinSet($url){
		global $total,$pages;
		requireComponent('Eolin.PHP.HTTPRequest');		
		$request = new HTTPRequest($url);
		if ($request->send()){
			$tmp = $request->responseText;
			 list($total, $pages, $data) =fetchTTSkinXmlVal($tmp);
			 return $data;
		}
		return null;
	}

	function TT_SkinManagerGetSkinInfo($url){
		global $total,$pages;
		requireComponent('Eolin.PHP.HTTPRequest');		
		$request = new HTTPRequest($url);
		if ($request->send()){
			$tmp = $request->responseText;
			 return fetchTTSkinInfoXmlVal($tmp);
		}
		return null;
	}

	function fetchTTSkinXmlVal( $DATA ){
		global $total,$pages;
		$info = array();
		$xmls = new XMLStruct();
		$outVal = array();
		if( !$xmls->open($DATA) ) {
			unset($xmls);	
			return null;
		}
		if( is_null(  $xmls->selectNodes('/response/skin_item') )){
			unset($xmls);	
			return null;
		}
		$tmp = $xmls->selectNode('/response/total');
		$total = $tmp['.value'];
		$tmp = $xmls->selectNode('/response/pages');
		$pages = $tmp['.value'];

		$tmp = $xmls->selectNode('/response/info_title');
		if(!empty($tmp)) $info['title'] = $tmp['.value'];
		$tmp = $xmls->selectNode('/response/info_link');
		if(!empty($tmp)) $info['link'] = $tmp['.value'];

		$i =0;
		foreach ($xmls->selectNodes('/response/skin_item') as $field) {
			$outVal[$i]['skin_id'] = $field['skin_id'][0]['.value'] ;
			$outVal[$i]['skin_new'] = $field['skin_new'][0]['.value'] ;
			$outVal[$i]['skin_set'] = $field['skin_set'][0]['.value'] ;
			$outVal[$i]['skin_downurl'] = $field['skin_downurl'][0]['.value'] ;
			$outVal[$i]['skin_preview'] = $field['skin_preview'][0]['.value'] ;
			$outVal[$i]['skin_version'] = $field['skin_version'][0]['.value'] ;
			$outVal[$i]['skin_name'] = $field['skin_name'][0]['.value'] ;
			$outVal[$i]['skin_description'] = $field['skin_description'][0]['.value'] ;
			$outVal[$i]['author_name'] = $field['author_name'][0]['.value'] ;
			$outVal[$i]['author_homepage'] = $field['author_homepage'][0]['.value'] ;
			$outVal[$i]['author_email'] = $field['author_email'][0]['.value'] ;
		$i++;
		}
		unset($xmls);	
		return array($total, $pages, $outVal, $info);
	}

	function fetchTTSkinInfoXmlVal( $DATA ){
		$skinfolders = array();
		$skinfiles = array();

		$xmls = new XMLStruct();
		$outVal = array();
		if( ! $xmls->open($DATA) ) {
			unset($xmls);	
			return null;
		}
		if( is_null(  $xmls->selectNodes('/response/skin_folder') )){
			unset($xmls);	
			return null;
		}
	
		$i =0;
		foreach ($xmls->selectNodes('/response/skin_folder') as $field) {
			$skinfolders[$i] = $field['.attributes']['name'];
			if(isset($field['files'])){
			foreach($field['files'] as $file){
				$skinfiles[$skinfolders[$i]][] = $file['.value'];
			}
			}

		$i++;
		}
		unset($xmls);	
		return array($skinfolders, $skinfiles);
	}

	function TT_SkinManagerSkinPrint($data){
		global $blogURL;
		$skin_preview = $data['skin_preview'];
		if(!empty($data['author_homepage'])){
			$author = "<a href=\"{$data['author_homepage']}\" target=\"_blank\" >{$data['author_name']}</a>";
		}else{
			$author = $data['author_name'];
		}
		$skin_set ="";
		if($data['skin_set'] > 1) $skin_set = "<span class=\"version\">".pluginLang::plts('컬러셋')." : {$data['skin_set']}".pluginLang::plts('종')." </span>";
?>
			<li>
				<div class="skin">
<?php
	if($data['skin_new'] == "1"){
?>
					<div class="newIcon">New!</div>
<?php
	}
?>
					<table border="0" cellpadding="0" cellspacing="0">
						<tr>
							<td><img src="<?php echo $data['skin_preview'];?>" alt="<?php echo $data['skin_id'];?>" width="120" height="120" /></td>
						</tr>
					</table>
				</div>
				<div class="skinInfo">
					<span class="title"><?php echo $data['skin_name'];?></span><br />
					<span class="version"><?php echo pluginLang::plts('버전');?> : <?php echo $data['skin_version'];?></span><br />
					<span class="maker"><?php echo pluginLang::plts('만든이');?> : <?php echo $author;?></span>
					<?php echo $skin_set;?><br />
				</div>
				<div class="buttons">
					<a href="#void" class="btn confirm" onclick="openPopup('<?php echo $blogURL."/plugin/TT_SkinManagerInfo/?skinname=".urlencode($data['skin_id'])."&amp;skindown=".urlencode($data['skin_downurl']);?>', 500, 400, '_TTskin','scrollbars=1');return false;"><?php echo pluginLang::plts('가져오기');?></a>
				</div>	
			</li>
<?php
}

function TT_SkinManagerSkinPrintSet($data){
	global $blogURL;
	$skin_preview = $data['skin_preview'];
	if(!empty($data['author_homepage'])){
		$author = "<a href=\"{$data['author_homepage']}\" target=\"_blank\" >{$data['author_name']}</a>";
	}else{
		$author = $data['author_name'];
	}
?>
			<li>
				<div class="skin">
				  <table border="0" cellpadding="0" cellspacing="0">
                    <tr><td><img src="<?php echo $data['skin_preview'];?>" alt="<?php echo $data['skin_id'];?>" width="120" height="120" /></td></tr>
                  </table>
					<div class="buttons">
				  		<a href="#void" class="btn confirm" onclick="location.href ='<?php echo $blogURL."/plugin/TT_SkinManagerGet/?skinname=".urlencode($data['skin_id'])."&amp;skindown=".urlencode($data['skin_downurl']);?>';"><?php echo pluginLang::plts('스킨 다운로드');?></a>
					</div>
				</div>
				<div class="skinInfo">
				<span class="title"><?php echo $data['skin_name'];?></span>
				<span class="version"><?php echo pluginLang::plts('버전');?> : <?php echo $data['skin_version'];?></span>
				<span class="maker"><?php echo pluginLang::plts('폴더명');?> : <?php echo $data['skin_id'];?></span>				
				<span class="maker"><?php echo pluginLang::plts('만든이');?> : <?php echo $author;?></span>
				<span class="comment"><?php echo nl2br($data['skin_description']);?></span>
				</div>	
			</li>
<?php
}

function TT_SkinManagerSaveSkinfiles($savefolder,$savename, $fileurl){
		$savefile = $savefolder."/".$savename;
		if(!@chmod($savefolder,0777)){
			die('파일저장 권한이 없습니다.');
		}
		requireComponent('Eolin.PHP.HTTPRequest');
		$request=new HTTPRequest($fileurl);
		$request->pathToSave=$savefile;
		if(!$request->send()){
			die('파일을 가져올 수 없습니다.');
		}
}

function TT_confirmHost($useMember = false){
	global $blogid, $service,$pluginURL;
	if($useMember == false){
		if(($service['type']=='single') || (getUserId()==1)){
			return true;
		}else{
			echo "<p class=confirmHost><img src=\"$pluginURL/image/icon_notice.gif\" alt=\"\" /> ".pluginLang::plts('스킨매니저 플러그인은 블로그 개설자에게 사용권한이 있습니다.')."</p>";		
			return false;			
		}
	}
	return true;				
}

if( !function_exists('getUserId')){
	function getUserId(){
		return empty($_SESSION['userid'])?false:$_SESSION['userid'];
	}
}

if( !function_exists('doesHaveOwnership')){
	function doesHaveOwnership(){
		global $blogid;
		if(empty($_SESSION['userid'])||($_SESSION['userid']!=$blogid))
			return false;
		return true;
	}
}

if( !function_exists('array_sort')){
	function array_sort($array, $type='asc'){
		$result=array();
		foreach($array as $var => $val){
			$set=false;
			foreach($result as $var2 => $val2){
				if($set==false){
					if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
						$temp=array();
						foreach($result as $var3 => $val3){
							if($var3==$var2) $set=true;
							if($set){
								$temp[$var3]=$val3;
								unset($result[$var3]);
							}
						}
						$result[$var]=$val;    
						foreach($temp as $var3 => $val3){
							$result[$var3]=$val3;
						}
					}
				}
			}
			if(!$set){
				$result[$var]=$val;
			}
		}
		return $result;
	}
}

if(!doesHaveOwnership()) die(pluginLang::plts('관리자만 접근할 수 있습니다.'));

?>
